<?php
/**
 * Created by PhpStorm.
 * User: 12133
 * Date: 2024/2/22
 * Time: 10:14
 */

namespace app\controller\phone;


use think\facade\Db;

class Bangmang extends Base
{
    public function index($moble = 'pachong')
    {
        $config = cache('yemian');
        if ($moble == 'pachong') {
            $data = [];
            $address = [
                '市本级',
                '鹿城区',
                '龙湾区',
                '瓯海区',
                '洞头区',
                '乐清市',
                '瑞安市',
                '永嘉县',
                '文成县',
                '平阳县',
                '泰顺县',
                '苍南县',
                '龙港市海经区高新区(经开区)'
            ];
            $area = Db::name('bangmang_qiyeyuanqu')
                ->field('y_district,count(0) AS count')
                ->group('y_district')
                ->select();
            foreach ($address AS $key => $value){
                $data[$key] = [
                    'y_district' => $value,
                    'count' => 0
                ];
                foreach ($area AS $index => $item){
                    if ($value == $item['y_district']){
                        $data[$key]['count'] = $item['count'];
                    }
                }
            }
            $list = Db::name('bangmang_qiyeyuanqu')->select();
            return $this->view('/phone/' . $moble, ['area' => $data,'list' => $list,'config' => $config]);
        }elseif($moble == 'pachong_list'){
            $area = input('area');
            $list = Db::name('bangmang_qiyeyuanqu')
                ->where('y_district',$area)
                ->select();
            return $this->view('/phone/' . $moble, ['list' => $list]);
        }else{
            $id = input('id');
            $info = Db::name('bangmang_qiyeyuanqu')->where('id', $id)->find();
            $list = Db::name('bangmang_qiye')->where('yid',$info['y_uid'])->select();
            return $this->view('/phone/' . $moble, ['list' => $list,'info' => $info]);
        }
    }
    public function zhuaData(){
        try {
            $url = 'https://y.qianzhan.com/system/GetTableData2';
            for ($i = 1; $i < 5000; $i++) {
                $data = [
                    'page' => $i,
                    'pageSize' => 40,
                    'queryStr' => '',
                    'level' => 3,
                    'NodeType' => 0,
                    'Node1' => 33,
                    'Node2' => 3303,
                    'Node3' => '',
                    'Node4' => '',
                    'match' => 0,
                    'agg' => 1,
                    'sort' => '',
                    'way' => 'desc'
                ];
                $data = $this->curl($url, $data, [
                    'Content-Type:application/x-www-form-urlencoded; charset=UTF-8',
                    'Cookie:qznewsite.uid=pqodnnbydgs1x4d5ikve1zlq; Hm_lvt_311e89cbd04a90da25b9aebdf23be56d=1708567790; Hm_lpvt_311e89cbd04a90da25b9aebdf23be56d=1708567807',
                    'Origin:https://y.qianzhan.com',
                    'Referer:https://y.qianzhan.com/system/index/',
                    'Sec-Ch-Ua:"Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"',
                    'Sec-Ch-Ua-Mobile:?0',
                    'Sec-Ch-Ua-Platform:"Windows"',
                    'Sec-Fetch-Dest:empty',
                    'Sec-Fetch-Mode:cors',
                    'Sec-Fetch-Site:same-origin',
                    'User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
                    'X-Requested-With:XMLHttpRequest'
                ]);
                $data = json_decode($data, true);
                if (empty($data['list'])) break;
                $install = [];
                foreach ($data['list'] AS $key => $value) $install[] = $value;
                Db::name('bangmang_qiyeyuanqu')->insertAll($install);
            }
        }catch (\Exception $e){
            dd($e->getTraceAsString());
        }
        dd('OK');
    }

    public function zhuaInfo(){
        $start = input('start',0);
        $number = input('number',30);
        $server = new \app\service\Keyword();
        $data = Db::name('bangmang_qiyeyuanqu')
            ->limit($start,$number)
            ->select();
//        foreach ($data AS $key => $value) {
//            $html = $server->curl('https://y.qianzhan.com/yuanqu/item/' . $value['y_uid'] . '.html', []);
//            $pattern = '/<div class="line2">(.*?)<\/div>/s';
//            if (preg_match($pattern, $html, $matches))
//                $extractedString = $matches[1];
//            else
//                continue;
//            $extractedString = str_replace(['\r', '\n', '<p>', '</p>', ' '], '', $extractedString);
//            Db::name('bangmang_qiyeyuanqu')->where('y_uid', $value['y_uid'])->update(['info' => $extractedString]);
//        }
        foreach ($data AS $key => $value){
            $url = 'https://y.qianzhan.com/yuanqu/loadComps?yid='.$value['y_uid'].'&page=1';
            $html = $this->curl(
                $url,
                [],
                ['Content-Type:application/x-www-form-urlencoded; charset=UTF-8']
            );
            // 提取cid属性和<td>内容
            // 分割<tr>标签
            preg_match_all('/<tr(.*?)>(.*?)<\/tr>/s', $html, $trMatches);
//            dd($trMatches);
//            preg_match('/cid="([^"]+)"/', $trMatches[1], $cidMatch);
//            $cid = isset($cidMatch[1]) ? $cidMatch[1] : '';
            // 使用explode和trim来分割和清理<td>内容
            // 遍历每个<tr>
            foreach ($trMatches[2] AS $index => $trContent) {
                // 提取cid属性和<td>内容
                if ($index == 0) continue;
//                preg_match('/cid="([^"]+)"/', $trContent, $cidMatch);
//                $cid = isset($cidMatch[1]) ? $cidMatch[1] : '';
                preg_match_all('/<td(.*?)>(.*?)<\/td>/s', $trContent, $tdContent);
                preg_match('/<a(.*?)>(.*?)<\/a>/s', $tdContent[2][1], $name);
                preg_match('/<p(.*?)>(.*?)<\/p>/s', $tdContent[2][4], $info);
                $install[] = [
                    'yid' => $value['y_uid'],
                    'name' => $name[2],
                    'info' => $info[2],
                    'money' => $tdContent[2][2],
                    'date' => $tdContent[2][3]
                ];
            }
        }
//        dd($install);
        if (!empty($install))
            Db::name('bangmang_qiye')->insertAll($install);
        return '';
    }

    public function curl($url, $post_data = [], $header = "", $data_type = ""){
        $header = empty($header) ? '' : $header;
        if($data_type == 'json'){
            $post_string = json_encode($post_data);
        }elseif($data_type == 'array') {
            $post_string = $post_data;
        }elseif(is_array($post_data)){
            $post_string = http_build_query($post_data, '', '&');
        }
        $ch = curl_init();    // 启动一个CURL会话
        curl_setopt($ch, CURLOPT_URL, $url);     // 要访问的地址
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 对认证证书来源的检查   // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        //curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        //curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($ch, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);     // Post提交的数据包
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);     // 设置超时限制防止死循环
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        //curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     // 获取的信息以文件流的形式返回
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头
        $result = curl_exec($ch);
        // 打印请求的header信息
        //$a = curl_getinfo($ch);
        //var_dump($a);
        curl_close($ch);
        return $result;
    }
}